const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

//引入路由
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/user');

//配置express
const app = express();

// 视图引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//配置日志
app.use(logger('dev'));
//配置express中间件解析json
app.use(express.json());
//配置express中间件解析表单中的url-encoded 格式的请求体数据
app.use(express.urlencoded({ extended: false }));
//配置读取cookie的插件
app.use(cookieParser());
//配置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

//配置路由
app.use('/', indexRouter);
app.use('/user', usersRouter);

// 捕获404并转发到错误处理程序
app.use(function(req, res, next) {
  next(createError(404));
});

// 配置错误信息
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


//导出
module.exports = app;
